package com.tzvtc.server.commons.security;

import cn.hutool.jwt.JWTUtil;
import com.alibaba.fastjson2.JSONObject;
import com.tzvtc.server.account.bean.PermissionBean;
import com.tzvtc.server.account.service.PermissionService;
import com.tzvtc.server.commons.bean.ResultBean;
import com.tzvtc.server.commons.exception.NormalException;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Order(1)
public class TokenFilter implements Filter {


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        // 设置返回的数据是json格式的，并且， 是utf-8编码
        servletResponse.setContentType("application/json;charset=utf-8");
        // 获取请求的路径
        String uri = request.getRequestURI();

        //如果用户访问的路径没有存储与数据库中， 不允许访问
        if(!SecurityLocal.permissionMap.containsKey(uri)){
            return;
        }
        //如果用户访问的路径存在于数据库中， 判断路径的权限类型
        PermissionBean permissionBean = SecurityLocal.permissionMap.get(uri);
        // 如果用户访问的路径的权限类型是1，说明不拦截，直接放行
        if (permissionBean.getType()==1){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }else if (permissionBean.getType()==2){
            // 如果用户访问的路径的权限类型是2，说明需要登录，检查token是否可用
            String token = request.getHeader("token");
            if (token==null){
                // 如果token不存在，直接返回一个json格式的字符串，表明请求失败
                servletResponse.getWriter().write(JSONObject.toJSONString(ResultBean.fail("无权限")));
                return;
            }
            boolean flg = JWTUtil.verify(token, "1234".getBytes());
            if (!flg){
                servletResponse.getWriter().write(JSONObject.toJSONString(ResultBean.fail("无权限")));
                return;
            }
            filterChain.doFilter(servletRequest,servletResponse);
        }

        SecurityLocal.clear();
    }
}
